import copy
from datetime import timedelta, datetime
from config import class_time

school_cal = []
a_week = timedelta(days=7)
a_day = timedelta(days=1)
day_chinese = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天']


def _str2date(date_str):
    year, month, date = date_str.split('-')
    start_date = datetime(int(year), int(month), int(date))
    return start_date.date()


def _get_all_date(start_date):
    dates = [start_date]
    for i in range(6):
        start_date = start_date + a_day
        dates.append(start_date)
    return dates


# 校历开始日期，总周数
def generate_cal(start_date_str, total_week):
    d = _str2date(start_date_str)
    school_cal.append(_get_all_date(d))
    for i in range(total_week - 1):
        d = d + a_week
        school_cal.append(_get_all_date(d))

    # for i, d in enumerate(school_cal):
    #     print(i, d)


# input 第几周的星期几，后面如果还有-0=所有周，-1=代表单周，-2=双周返回具体日期
# 例如 4-11周的周二--- 4-11,2
def cal_date(lesson):
    lessons = []
    for week_range in lesson[3]:
        dash_count = week_range.count('-')
        week_odd_even = 0
        if dash_count == 0:
            start, end = week_range, week_range
        elif dash_count == 1:
            start, end = week_range.split('-')
        elif dash_count == 2:
            start, end, week_odd_even = week_range.split('-')
        start, end, week_odd_even = int(start), int(end), int(week_odd_even)
        for i in range(start, end + 1):
            if week_odd_even == 1:
                if i % 2 == 0:
                    continue
            elif week_odd_even == 2:
                if i % 2 != 0:
                    continue
            days = school_cal[int(i) - 1]
            date_ = days[int(lesson[0]) - 1]
            clone_lesson = copy.deepcopy(lesson)
# [1, datetime.date(2024, 8, 26), '星期一', '1-4', '08:00-11:50', '大学生创新创业教育', ['1-20'], '张忠杰', '无', 90, '未安排', '课程学时组成：实践:320', '板块等级：无', '场地类别：多媒体教室']
            clone_lesson.insert(0,i)   # 第几周)
            clone_lesson.insert(1, date_) # 日期
            clone_lesson[2] = day_chinese[date_.weekday()]  # 星期几
            clone_lesson.insert(3,lesson[2])  # 第几节课
            clone_lesson.insert(4,class_time.get(lesson[2]))  # 第几节课
            del clone_lesson[6]
            del clone_lesson[6]
            lessons.append(clone_lesson)
    return lessons
